/**
 * 从S到T的最少步数，只有在*位置才能转弯（也可以不转，但不能掉头）
 * BFS
 */
#include <bits/stdc++.h>
#include <bits/extc++.h>
using namespace std;

template <typename T>
const T & mymax(const T & a, const T & b){
    return max(a, b);
}

template<typename T, typename ... Args>
const T & mymax(const T & t, const Args & ... args){
    return max(t, mymax(args ...));
}

template<typename T>
void input(vector<T> & v, int n){
	v.assign(n + 1, {});
    for(int i=1;i<=n;++i) cin >> v[i];
	return;
}

template<typename T>
istream & operator >> (istream & is, vector<T> & v){
	for(auto & i : v) is >> i;
	return is;
}

using llt = long long;
using vi = vector<int>;
using vll = vector<llt>;
using pii = pair<int, int>;
using vpii =vector<pii>;

int const DR[] = {-1, 1, 0, 0};
int const DC[] = {0, 0, -1, 1};

int N, M;
vector<string> Board;
array<vector<vi>, 4> Flag;

int proc(){
    using ppii = pair<pii, int>;
    queue<ppii> q;
    
    int sx, sy, ex, ey;
    for(int i=0;i<N;++i)for(int j=0;j<M;++j){
        if('S' == Board[i][j]){
            sx = i; sy = j;
        }
        if('T' == Board[i][j]){
            ex = i; ey = j;
        }
    }

    for(int i=0;i<4;++i) {
        Flag[i].assign(N, vi(M, 0));
        Flag[i][sx][sy] = 1;
    }

    q.push({{sx, sy}, 0});
    q.push({{sx, sy}, 1});
    q.push({{sx, sy}, 2});
    q.push({{sx, sy}, 3});
    

    int ans = 0;
    int sz = 0;
    while(sz = q.size()){
        ans += 1;
        while(sz--){
            auto h = q.front(); q.pop();

            int nr = h.first.first + DR[h.second];
            int nc = h.first.second + DC[h.second];
            if(0 <= nr and nr < N and 0 <= nc and nc < M and '#' != Board[nr][nc]){
                if('T' == Board[nr][nc]) return ans;
                if('.' == Board[nr][nc]){
                    if(0 == Flag[h.second][nr][nc]){
                        Flag[h.second][nr][nc] = 1;
                        q.push({{nr, nc}, h.second});
                    }
                }
                if('*' == Board[nr][nc]){
                    for(int i=0;i<4;++i){
                        if((i ^ h.second) == 1) continue;

                        if(0 == Flag[i][nr][nc]){
                            Flag[i][nr][nc] = 1;
                            q.push({{nr, nc}, i});
                        }                        
                    }     
                }
            }
        }
    }
    return -1;
}

void work(){
    cin >> N >> M;
    Board.assign(N, {});
    cin >> Board;
    cout << proc() << "\n";
}

int main(){
#ifndef ONLINE_JUDGE
    freopen("z.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(0);   
    int nofkase = 1;
    cin >> nofkase;
    while(nofkase--) work();
    return 0;
}